package com.ustadzmenjawab.crawler;

import java.io.IOException;
import java.util.Set;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import com.google.gwt.dev.util.collect.HashSet;
import com.ustadzmenjawab.shared.Article;

public class MediaUmatCrawler extends CrawlerRoot {
	public static final String HOME_URL = "http://mediaumat.com/ustadz-menjawab.html";
	public static final String PATTERN = "/ustadz-menjawab";
	@Override
	public boolean isRelevantURL(String url) {
		if(url.contains("/label/") || url.contains("_archive") 
				|| url.contains("#") || url.contains("/feeds/") 
				|| url.contains(".pdf")
				|| url.contains("print=1")
				|| url.contains("mailto")
			)
			return false;
		if(url.contains(PATTERN))
			return true;
		return false;
	}

	@Override
	public boolean isRelevantPage(String content) {
		if(getQuestion(content) != null){
			return true;
		}
		return false;
	}
	
	public boolean isRelevantPage(String url, String content){
		if(!url.contains(PATTERN+"/") && url.equalsIgnoreCase(PATTERN)){
			return false; 
		}
		return isRelevantPage(content);
	}

	@Override
	public String getTitle(String body) {
		Document doc = Jsoup.parse(body);
		Element p = doc.select("td[class*=contentheading]").first();
		return p.text();
	}

	@Override
	public String getQuestion(String body) {
	//	Document doc = Jsoup.parse(body);
		body =getArticle(body);
		int istart = body.indexOf("Pertanyaan:");
		if(istart == -1){
			istart = body.indexOf("Pertanyaan :");
		}
		if(istart == -1){
			istart = body.indexOf("Pertanyaan;");
		}
		if(istart == -1){
			istart = body.indexOf("Tanya:");
		}
		if(istart == -1){
			istart = body.indexOf("Tanya :");
		}
		int iend = body.indexOf("Jawaban:");
		if(iend == -1)
		{
			iend = body.indexOf("Jawaban :");
		}
		if(iend == -1)
		{
			iend = body.indexOf("Jawab:");
		}
		if(iend == -1)
		{
			iend = body.indexOf("Jawab :");
		}
		if(istart == -1 || iend == -1 ){
			return null;
		}
		String subbody = body.substring(istart, iend);
		return subbody;
	}

	@Override
	public String getArticle(String body) {
		Document doc = Jsoup.parse(body);
		Element p = doc.select("table[class*=contentpaneopen]").get(1);
		String text = p.text();
		return text;
	}

	@Override
	public boolean insertContent(String url, String content) {
		try{
			Article article = new Article();
			String title = getTitle(content);
			if(isTitleExist(title, "mediaumat.com")){
				return false;
			}
			article.setJudul(title);
			article.setKategori("shariah");
			article.setSumber("mediaumat.com");
			article.setTahun("2011");
			article.setUrl(url);
			article.setUstadz("M Shiddiq Al Jawi");
			article.setArtikel(getArticle(content));
			article.setPertanyaan(getQuestion(content));
			db.insertArticle(article);
			return true;
		}catch(Exception e){
			System.out.println(" exception "+e.getClass() +" :" + e.getMessage());
			e.printStackTrace();
			insertFailure(url,"exception "+e.getClass() +" :" + e.getMessage());
			return false;
		}
	}
	
	public static void main(String[] args){
		try {
			MediaUmatCrawler cr = new MediaUmatCrawler();
			Document doc = Jsoup.connect(HOME_URL).timeout(0).get();
			Elements unvisited = doc.select("a[href]");
			Set<String> visited = new HashSet<String>();
			while(unvisited.size() > 0){
				Element link = unvisited.first();
					try{
						String absHref = link.attr("abs:href");
						unvisited.remove(link);
						if(!visited.contains(absHref.toLowerCase())){
							visited.add(absHref.toLowerCase());
							if(cr.isRelevantURL(absHref)){
								Document page = Jsoup.connect(absHref).timeout(0).get();
								String content = page.html();
								Elements pageLinks = page.select("a[href]");
								for(Element newlink : pageLinks){
									String newLinkStr = newlink.attr("abs:href").toLowerCase();
									if(!visited.contains(newLinkStr) && cr.isRelevantURL(newLinkStr))
									{
										unvisited.add(newlink);
									}
								}
								if(cr.isRelevantPage(absHref,content)){
									System.out.println(absHref + " is a relevant page");
									
									if(!cr.isUrlExist(absHref)){
										cr.insertContent(absHref, content);
									}
								}else{
									System.out.println(absHref + " is not a relevant page");
								}
							}
						}
					}catch(Exception e){
						System.out.println(" exception "+e.getClass() +" :" + e.getMessage());
						e.printStackTrace();
					}
				}
		}
		catch (IOException e) {
			e.printStackTrace();
		}

	}
}
